<?php


namespace app\admin\controller;


use app\common\controller\admin\Base;
use app\admin\model\AppBase;

class Partner extends Base
{
    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Partner;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $adminId = $this->request->post('admin_id', '');
            $name = $this->request->post('name', '');
            $status = $this->request->post('status', '');

            if ($adminId != '') {
                $where['admin_id'] = $adminId;
            }
            if ($status != '') {
                $where['status'] = $status;
            }
            if ($name != '') {
                $where['name'] = ['like', '%' . $name . '%'];
            }
            $where['is_del'] = 0;
            $list = $this->model
                ->field('*')
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select()
                ->toArray();
            $appBaseList = AppBase::select()->toArray();
            $appBaseList = array_column($appBaseList, null, 'id');
            foreach ($list as $key => $value) {
                $appIds = explode(',', $value['app_id']);
                $appBaseNames = [];
                foreach ($appIds as $v) {
                    if (!empty($appBaseList[$v])) {
                        $appBaseNames[] = $appBaseList[$v]['title'];
                    }
                }
                $value['app_base_name_list'] = $appBaseNames;
                //显示每日可分配跟已分配
                //取出所有合作方下的客服账号
                $accountModel = new \app\admin\model\CustomerServiceAccount();
                $accountList = $accountModel->with(['CustomerServiceAccountMiddle'])->where([
                    'partner_id' => $value['id'],
//                    'status' => 1,
//                    'switch' => 1
                ])
                    ->select();
                $value['assigned_user_num'] = Statistics::getAssignedUserNum($accountList);
                $list[$key] = $value;
            }
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }
}